/**
 * Created by Administrator on 2017/1/16.
 */

var MJPlayer = require('../MJ/player').MJPlayer;
var MJ = require('../MJ/MJ');
var Const = require('./const');

exports.GYMJPlayer = MJPlayer.extend({

    init: function(uid, msg) {
        this._super(uid, msg);

        this._stat.zmCount = 0;             // 自摸次数
        this._stat.dpCount = 0;             // 点炮次数
        this._stat.dhCount = 0;             // 点胡次数
        this._stat.anGangCount = 0;        // 暗杠次数
        this._stat.mingGangCount = 0;      // 明杠次数

        this._stat.remainScore = 1000;// 剩余积分
        this._stat.roundJiScore = 0; // 本轮鸡分
        this._stat.roundJiCards = {};// 本轮鸡牌{牌值:数量}
        this._stat.scoreHistory = [];// 每轮积分详情
    },

    addRoundJiScore: function(score) {
        this._stat.roundJiScore += score;
    },

    settlementGangScore: function() {
        var player = this;
        var room = this.getRoom();

        // 抢杠烧豆
        var isQGSD = room.getOption('QGSD') && (player.existRoundScoreRule(Const.ScoreRule.QG) || player.existRoundScoreRule(Const.ScoreRule.GSP));
        if (isQGSD) {
            player.setRoundScoreRule("QGSD");
        }

        // 豆全包
        var douScore = 3;
        var DQBScores = {};

        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];
            var isNoScore = (gangInfo.overdue || gangInfo.unscored);
            if (gangInfo.gang == MJ.Gang.DIAN) {
                var fromPlayer = room.getPlayerByIndex(gangInfo.from);
                if (fromPlayer) {
                    if (!player.isRoundTing()) {
                        if (fromPlayer.isRoundTing()) {
                            ExObject.addNumber(DQBScores, fromPlayer.getIndex(), douScore);
                        }
                    } else if (!isQGSD && !isNoScore) {
                        fromPlayer.addRoundGangScore(-douScore);
                        player.addRoundGangScore(douScore);
                    }
                }
            } else {
                room.enumPlayers(function(eIndex, ePlayer) {
                    if (eIndex != player.getIndex()) {
                        if (!player.isRoundTing()) {
                            if (ePlayer.isRoundTing()) {
                                ExObject.addNumber(DQBScores, eIndex, douScore);
                            }
                        } else if (!isQGSD && !isNoScore) {
                            ePlayer.addRoundGangScore(-douScore);
                            player.addRoundGangScore(douScore);
                        }
                    }
                });
            }
        }

        if (!player.isRoundTing() && room.getOption('DQB')) {
            var DQBScore = 0;
            ExObject.eachKeyNum(DQBScores, function(eIndex, score) {
                var targetPlayer = room.getPlayerByIndex(eIndex);
                if (targetPlayer) {
                    targetPlayer.addRoundScore(score);
                    targetPlayer.addRoundScoreDetail(Const.ScoreReason.BG, score);
                    DQBScore += score;
                }
            });

            if (DQBScore) {
                player.addRoundScore(-DQBScore);
                player.addRoundScoreDetail(Const.ScoreReason.BG, -DQBScore);
            }
        }
    },

    settlementJiScore: function() {
        var player = this;
        var room = this.getRoom();
        var jiCards = room.getJiCards();

        var isJQB = room.getOption('JQB');
        var isMTJ = room.getOption('MTJ');

        var isQGSJ = room.getOption('QGSJ') && (player.existRoundScoreRule(Const.ScoreRule.QG) || player.existRoundScoreRule(Const.ScoreRule.GSP));
        if (isQGSJ) {
            player.setRoundScoreRule(Const.ScoreRule.QGSJ);
        }

        // 包鸡
        var isBJ = (!player.isRoundTing()) ? true : false;
        var jiScore = 0; // 基础鸡分
        var bjScores = {};
        var roundJiCards = this._stat.roundJiCards;

        var playCards = this.getPlayCards();
        var objPlayCards = {};
        playCards.forEach(function(card) {
            ExObject.addNumber(objPlayCards, card, 1);
        });

        ExObject.eachKeyNum(objPlayCards, function(card, num) {
            var jiCard = jiCards[card];
            if (jiCard) {
                var score = jiCard.getBaseScore() * num;
                if (jiCard.isCF() && jiCard.getFrom() == player.getIndex()) {
                    score += jiCard.getBaseScore();
                }

                if (isBJ) {
                    if (room.isDefaultJiCard(card)) {
                        //ExObject.addNumber(roundJiCards, card, num);
                        room.enumPlayers(function(eIndex, ePlayer) {
                            ExObject.addNumber(bjScores, eIndex, score);
                        });
                    }
                } else if (!isQGSJ) {
                    if (isMTJ || room.isDefaultJiCard(card)) {
                        ExObject.addNumber(roundJiCards, card, num);
                        jiScore += score;
                    }
                }
            }
        });

        this._pengCards.forEach(function(card) {
            var jiCard = jiCards[card];
            if (jiCard) {
                var score = 3 * jiCard.getBaseScore();

                if (isBJ) {
                    if (room.isDefaultJiCard(card)) {
                        //ExObject.addNumber(roundJiCards, card, 3);
                        room.enumPlayers(function(eIndex, ePlayer) {
                            ExObject.addNumber(bjScores, eIndex, score);
                        });
                        if (jiCard.isZR() && jiCard.getOwner() == player.getIndex()) { // 给打出冲锋鸡的玩家多包1个鸡分
                            var fromPlayer = room.getPlayerByIndex(jiCard.getFrom());
                            if (fromPlayer) {
                                ExObject.addNumber(bjScores, jiCard.getFrom(), jiCard.getBaseScore());
                            }
                        }
                    }
                } else if (!isQGSJ) {
                    ExObject.addNumber(roundJiCards, card, 3);
                    jiScore += score;
                }
            }
        });

        this._gangCards.forEach(function(gang) {
            var card = gang.card;
            var jiCard = jiCards[card];
            if (jiCard) {
                var score = 4 * jiCard.getBaseScore();

                if (isBJ) {
                    if (room.isDefaultJiCard(card)) {
                        //ExObject.addNumber(roundJiCards, card, 4);
                        room.enumPlayers(function(eIndex, ePlayer) {
                            ExObject.addNumber(bjScores, eIndex, score);
                        });
                        if (jiCard.isZR() && jiCard.getOwner() == player.getIndex()) { // 给打出冲锋鸡的玩家多包1个鸡分
                            var fromPlayer = room.getPlayerByIndex(jiCard.getFrom());
                            if (fromPlayer) {
                                ExObject.addNumber(bjScores, jiCard.getFrom(), jiCard.getBaseScore());
                            }
                        }
                    }
                } else if (!isQGSJ) {
                    ExObject.addNumber(roundJiCards, card, 4);
                    jiScore += score;
                }
            }
        });

        ExObject.eachKeyNum(this._handCards.getCards(), function(card, num) {
            var jiCard = jiCards[card];
            if (jiCard) {
                var score = num * jiCard.getBaseScore();
                if (isBJ) {
                    // 手牌不参与包鸡
                } else if (!isQGSJ) {
                    ExObject.addNumber(roundJiCards, card, num);
                    jiScore += score;
                }
            }
        });

        if (isBJ && isJQB) { // 责任鸡打出冲锋鸡的玩家未下叫也要包
            ExObject.each(jiCards, function(card, jiCard) {
                if (jiCard.isZR() && (player.getIndex() == jiCard.getFrom())) {
                    room.enumPlayers(function(eIndex, ePlayer) {
                        if (eIndex != jiCard.getOwner()) {
                            ExObject.addNumber(bjScores, eIndex, jiCard.getBaseScore()*2);
                        }
                    });
                }
            });
        }

        if ((this._stat.roundResult == MJ.Result.DH) && this._stat.huCard) {
            var card = this._stat.huCard;
            var jiCard = jiCards[card];
            if (jiCard) {
                if (!isQGSJ) {
                    ExObject.addNumber(roundJiCards, card, 1);
                    jiScore += jiCard.getBaseScore();
                }
            }
        }

        if (isBJ) {
            var totalBJScore = 0;
            ExObject.eachKeyNum(bjScores, function(eIndex, eScore) {
                if (eIndex != player.getIndex()) {
                    var ePlayer = room.getPlayerByIndex(eIndex);
                    if (ePlayer && ePlayer.isRoundTing()) {
                        ePlayer.addRoundScore(eScore);
                        ePlayer.addRoundScoreDetail(Const.ScoreReason.BJ, eScore);
                        totalBJScore += eScore;
                    }
                }
            });

            if (totalBJScore) {
                player.addRoundScore(-totalBJScore);
                player.addRoundScoreDetail(Const.ScoreReason.BJ, -totalBJScore);
            }
        } else {
            room.enumPlayers(function(eIndex, ePlayer) {
                if (eIndex != player.getIndex()) {
                    ePlayer.addRoundJiScore(-jiScore);
                    player.addRoundJiScore(jiScore);
                }
            });

            ExObject.each(jiCards, function(card, jiCard) {
                if (jiCard.isZR() && (player.getIndex() == jiCard.getOwner())) {
                    var zrPlayer = room.getPlayerByIndex(jiCard.getFrom());
                    if (zrPlayer) {
                        var score = jiCard.getBaseScore();
                        zrPlayer.addRoundJiScore(-score);
                        player.addRoundJiScore(score);
                    }
                }
            });
        }
    },

    settlementPatternScore: function() {
        var player = this;
        var room = this.getRoom();

        if (player.existRoundScoreRule(Const.ScoreRule.QG)) {
            var qgs = room.getOption("QGS") || room.getHideOption("QGS");
            var qgScores = {};
            if (qgs == 1) {
                room.enumPlayers(function(eIndex, ePlayer) {
                    if (eIndex != player.getIndex() && ePlayer.isRoundHu()) {
                        ExObject.addNumber(qgScores, eIndex, 9);
                    }
                });
            } else if (qgs == 2) { // 抢杠包N家
                room.enumPlayers(function(eIndex, ePlayer) {
                    if (eIndex != player.getIndex() && ePlayer.isRoundTing()) {
                        ExObject.addNumber(qgScores, eIndex, Const.PatternScore[ePlayer.getRoundPattern()] || 0);
                        if (ePlayer.isRoundHu()) {
                            ExObject.addNumber(qgScores, eIndex, 9);
                        }
                    }
                });
            }

            var totalQGScore = 0;
            ExObject.eachKeyNum(qgScores, function(eIndex, score) {
                var targetPlayer = room.getPlayerByIndex(eIndex);
                if (targetPlayer) {
                    targetPlayer.addRoundScore(score);
                    targetPlayer.addRoundScoreDetail(Const.ScoreReason.QG, score);
                    totalQGScore += score;
                }
            });

            if (totalQGScore) {
                player.addRoundScore(-totalQGScore);
                player.addRoundScoreDetail(Const.ScoreReason.QG, -totalQGScore);
            }
        }

        if (!this.isRoundHu()) {
            return;
        }

        var isLZ = room.getOption('LZ');
        var lzScore = room.getDealerLZ();
        var lzScores = {};
        //if (isLZ && player.getIndex() == room.getDealerIndex() && room.getDealerLZ() > 0) {
        //    this.addRoundItemScores(Const.ScoreRule.LZ, lzScore);
        //}

        var isYQ = room.getOption("YQ");
        if (isYQ && (player.getInitColors().length < room.getSubConfig().colors.length)) {
            this.addRoundItemScores(Const.ScoreRule.YQ, 3);
        }

        // 结算牌型及基础分
        var basicScore = this._stat.roundPatternScore + ExObject.sumValue(this._stat.roundItemScores);

        this._stat.roundTarget.forEach(function(playerIndex) {
            var target = room.getPlayerByIndex(playerIndex);
            if (target) {
                target.addRoundScore(-basicScore);
                target.addRoundScoreDetail(player.getRoundResult(), -basicScore);
                player.addRoundScore(basicScore);

                if (target.isBaoTing()) {
                    var tingScore = Const.ItemScore[Const.ScoreRule.BT];
                    target.addRoundScore(-tingScore);
                    target.addRoundScoreDetail(Const.ScoreReason.BT, -tingScore);
                    player.addRoundScore(tingScore);
                    player.addRoundScoreDetail(Const.ScoreReason.BT, tingScore);
                }

                if (isLZ && room.getDealerLZ() > 0) {
                    if (player.getIndex() == room.getDealerIndex()) {
                        ExObject.addNumber(lzScores, player.getIndex(), lzScore);
                        ExObject.addNumber(lzScores, playerIndex, -lzScore);
                    }

                    if (target.getIndex() == room.getDealerIndex()) {
                        ExObject.addNumber(lzScores, player.getIndex(), lzScore);
                        ExObject.addNumber(lzScores, playerIndex, -lzScore);
                    }
                }
            }
        });

        ExObject.eachKeyNum(lzScores, function(eIndex, eScore) {
            var ePlayer = room.getPlayerByIndex(eIndex);
            if (ePlayer) {
                ePlayer.addRoundScore(eScore);
                ePlayer.addRoundScoreDetail(Const.ScoreReason.LZ, eScore);
            }
        });
    },

    settlementHZScore: function() {
        var player = this;
        var room = this.getRoom();

        if (player.isRoundTing()) {
            return;
        }

        var totalScore = 0;
        room.enumPlayers(function(eIndex, ePlayer) {
            if ((player.getIndex() != eIndex) && ePlayer.isRoundTing() && !ePlayer.isRoundHu()) {
                var score = Const.PatternScore[ePlayer.getRoundPattern()] || 0;
                totalScore += score;
                ePlayer.addRoundScore(score);
                ePlayer.addRoundScoreDetail(Const.ScoreReason.PT, score);
            }
        });

        player.addRoundScore(-totalScore);
        player.addRoundScoreDetail(Const.ScoreReason.PT, -totalScore);
    },

    settlement: function() {
        this._super();

        this.addRoundScore(this._stat.roundGangScore);
        this.addRoundScore(this._stat.roundJiScore);

        this._stat.scoreHistory.push(this.getRoundScore());
        this._stat.remainScore += this.getRoundScore();

        if (this._stat.roundResult == MJ.Result.ZM) {
            this._stat.zmCount++;
        } else if (this._stat.roundResult == MJ.Result.DH) {
            this._stat.dhCount++;
            if (this._stat.roundTarget.length > 0) {
                var dpPlayer = this.getRoom().getPlayerByIndex(this._stat.roundTarget[0]);
                if (dpPlayer) {
                    dpPlayer._stat.dpCount++;
                }
            }
        }

        for (var i = 0, l = this._gangCards.length; i < l; ++i) {
            var gangInfo = this._gangCards[i];
            if (gangInfo.gang == MJ.Gang.AN || gangInfo.gang == MJ.Gang.ANS) {
                this._stat.anGangCount++;
            } else {
                this._stat.mingGangCount++;
            }
        }
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getInfo: function() {
        var info = this._super();
        info.remainScore = this._stat.remainScore;
        return info;
    },

    getReconnectInfo: function(isSelf) {
        var info = this._super(isSelf);
        info.remainScore = this._stat.remainScore;
        return info;
    },

    getSettlementInfo: function() {
        var info = this._super();
        info.gangCards = this._gangCards;
        info.pengCards = this._pengCards;
        info.handCards = this._handCards.getCards();
        info.playCards = this.getPlayCards();
        return info;
    },

    onStartNewRound: function() {
        this._super();
        this._stat.roundJiScore = 0;
        this._stat.roundJiCards = {};
    },

    getInitHandCardPreCards: function() {
        var preCards = [];

        //var distance = this.getRoom().getIndexDistance(this.getIndex(), this.getRoom().getDealerIndex());
        //if (distance == 0) {
        //} else if (distance == 1) {
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 3));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 4));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 5));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 6));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 7));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 8));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 9));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 9));
        //    preCards.push(MJ.getValue(MJ.Color.TONG, 9));
        //    preCards.push(MJ.getValue(MJ.Color.TIAO, 4));
        //    preCards.push(MJ.getValue(MJ.Color.TIAO, 5));
        //    preCards.push(MJ.getValue(MJ.Color.TIAO, 6));
        //    preCards.push(MJ.getValue(MJ.Color.TIAO, 6));
        //}
        return preCards;
    },

    checkHuLogic: function(cards, huCard) {
        var pattern = this._super(cards, huCard);
        if (pattern == MJ.Pattern.NONE) {
            return pattern;
        }

        var colors = this.getColorsWithCards(cards);

        if (pattern == MJ.Pattern.SINGLE && !this.getRoom().getHideOption("patternSingle")) {
            pattern = MJ.Pattern.PAIR;
        }

        var exPattern = 0;
        if (colors.length == 1) {
            exPattern = 5;
        }

        if (pattern == Const.Pattern.PAIR7) {
            if (huCard == 0) { // 天胡
                if (this._handCards.getAnGangCards().length > 0) {
                    exPattern += 2;
                }
            } else {
                if (cards[huCard] == 4) {
                    exPattern += 2;
                }
            }
        }

        if (exPattern) {
            pattern = pattern*10 + exPattern;
        }

        return pattern;
    }
});